<template>
  <a-spin :spinning="spinning != 0">
    <a-card :bordered="false">
    <a-form :form="form"
            layout="horizontal"
            :hideRequiredMark="false"
            style="">
      <a-row  :gutter="0" style="margin-bottom:0px;">
        <a-col :span="16" >
          <a-form-item :label="$t('m.eform.apptable.entity.dataModel')" :label-col="{ span:4 }" :wrapper-col="{ span:18 }">
            <a-button type="primary" @click="selectERModel">
              {{ $t('m.codegen.button.select_er_model') }}
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row >
        <a-col  :span="21" :gutter="0">
          <a-row  style="margin-bottom:15px;">
            <a-col :span="3">

            </a-col>
            <a-col :span="21">
              <obj-relation-table ref="objRelationTable"
                                  :obj-relation="model.objRelation"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <a-row  :gutter="0">
        <a-col  :span="16">
          <a-form-item :label="$t('m.codegen.entity.templateType')" :label-col="{ span:4 }" :wrapper-col="{ span:18 }">
            <a-select
              style="width: 200px;"
              :disabled="disabledRules.templateType"
              v-decorator="['templateType', validatorRules.templateType]"
              :options="templeteOptions"
              @change="changeTemplateType"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row  :gutter="0" v-show="showManangerLayout">
        <a-col  :span="16">
          <a-form-item :label="$t('m.codegen.entity.mainManangerLayout')" :label-col="{ span:4 }" :wrapper-col="{ span:18 }">
            <a-radio-group
              :disabled="disabledRules.mainManangerLayout"
              v-decorator="['mainManangerLayout', validatorRules.mainManangerLayout]"
              :options="checkBoxOptions.mainManangerLayout"
            >
             <!-- <a-radio value="TB">上下</a-radio>
              <a-radio value="LR">左右</a-radio>-->
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row  :gutter="0">
        <a-col  :span="24">
          <a-row  :gutter="0">
            <a-col  :span="16">
              <a-form-item :label="$t('m.codegen.label.attribute_selection')" :label-col="{ span:4 }" :wrapper-col="{ span:18 }">
                <ych-checkbox :disabled="disabledRules.withAttachment"
                            v-decorator="['withAttachment', validatorRules.withAttachment]"
                            :options="checkBoxOptions.withAttachment"></ych-checkbox>
<!--                <ych-checkbox :disabled="disabledRules.withWorkflow"
                            v-decorator="['withWorkflow', validatorRules.withWorkflow]"
                            :options="checkBoxOptions.withWorkflow"></ych-checkbox>-->
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
      </a-row>

    </a-form>
    </a-card>
    <ERModelSelect ref="erModelSelect" @selectErModel="changeErModel"></ERModelSelect>
  </a-spin>
</template>

<script>

  import {FormMixin} from '@/mixins/FormMixin'
  import { getAction, httpAction } from '@/api/manage'
  import ERModelSelect from './ERModelSelect'
  import ObjRelationTable from './actAppObject/ObjRelationTable'
  import YchConstant from "@/api/YchConstant";
  import {YchCheckbox} from '@yuncheng/ych-components'

  export default {
    name: "TableformModal",
    mixins: [FormMixin],
    components: {
      ERModelSelect,
      ObjRelationTable,
      YchCheckbox
    },
    props: {
      iProps: {
        type: Object,
        default: () => {
        }
      },
      genConfigId:{
        type:String,
        default:""
      },
      objCode:{
        type:String,
        default:""
      }
    },
    data() {
      return {
        showManangerLayout:false,
        erModel:{},
        sysGenConfig:{},
        spinning: 0,//遮罩
        templeteOptions:[
          {
            value:'',
            label:this.$t('m.common.label.option_select')
          },
        ],
        validatorRules: {
          templateType: {
            initialValue:'',
            rules: [{ required: true, message: this.$t('m.codegen.verify.templateTypeValid') }]
          },
          withAttachment: {
            rules: []
          },
          withSubTable: {
            initialValue: false,
            rules: []
          },
          mainManangerLayout: {
            initialValue:'TB',
            rules: []
          },
        },
        disabledRules: {
          templateType: true,
          withAttachment: false,
          withSubTable: false,
          mainManangerLayout: false,
        },
        dictConfig: {},
        optionConfig: {},
        url: {
          queryBySysGenConfigId: YchConstant.PREFIX_EFORM + '/generator/manage/genConfig/queryBySysGenConfigId',
          saveGenConfigAndTable: YchConstant.PREFIX_EFORM + "/generator/manage/genConfig/saveGenConfigAndTable",
          getObjModelByCode:YchConstant.PREFIX_EFORM + '/manage/actAppObject/queryByCode'
        },


        checkBoxOptions: {
          withAttachment: [
            {
              label: this.$t('m.codegen.label.with_accessories'),
              value: "true"
            }
          ],
          mainManangerLayout:[
            {
              label:this.$t('m.codegen.label.layout_upDown'),
              value:"TB"
            },
            {
              label:this.$t('m.codegen.label.layout_leftRight'),
              value:"LR"
            }
          ]
        },

      }
    },
    methods: {
      selectERModel(){
        this.$refs.erModelSelect.showModal()
      },
      changeErModel(erModel){
        this.$nextTick(() => {
          this.form.setFieldsValue({templateType:''})
        })
        this.getErModel(erModel)
      },

      getErModel(erModel){
        this.$emit('setProp', 'erModel', erModel)
        this.erModel = erModel
        this.sysGenConfig.objCode = this.erModel.objCode
        this.model.tableName = erModel.relation.tableKey;
        this.$refs.objRelationTable.init(this.erModel.objRelation)
        this.initTemplate(erModel)
      },
      initTemplate(erModel){
        let subTableRelations = erModel.relation.children;
        if(subTableRelations && subTableRelations.length>0){
          this.templeteOptions = [
            {
              value:'',
              label:this.$t('m.common.label.option_select')
            },
            {
              value:'mainSubTabTiling',
              label:this.$t('m.codegen.label.templateType_mainSubTabTiling')
            },
            {
              value:'mainSubTabTilingFlow',
              label:this.$t('m.codegen.label.templateType_mainSubTabTilingFlow')
            },
            {
              value:'mainTilingSubTab',
              label:this.$t('m.codegen.label.templateType_mainTilingSubTab')
            },
            {
              value:'mainTilingSubTabFlow',
              label:this.$t('m.codegen.label.templateType_mainTilingSubTabFlow')
            },
            {
              value:'mainTiling',
              label:this.$t('m.codegen.label.templateType_mainTiling')
            },
            {
              value:'mainTilingFlow',
              label:this.$t('m.codegen.label.templateType_mainTilingFlow')
            },
          ]
        }else{
          this.templeteOptions = [
            {
              value:'',
              label:this.$t('m.common.label.option_select')
            },
            {
              value:'singleTable',
              label:this.$t('m.codegen.label.templateType_singleTable')
            },
            {
              value:'singleTableFlow',
              label:this.$t('m.codegen.label.templateType_singleTableFlow')
            },
          ]
        }
        let templateType = this.model.templateType;
        if(templateType!=''){
          this.changeTemplateType(templateType)
        }
        this.disabledRules.templateType = false
      },
      changeTemplateType(value){
        if(value=='mainTilingSubTab' || value=='mainTilingSubTabFlow'){
          this.showManangerLayout = true
        }else{
          this.showManangerLayout = false
        }
      },
      getObjModelByCode(objCode){
        let that = this
        that.spinning++
        let params = {
          codes:objCode
        }
        getAction(this.url.getObjModelByCode, params).then(res => {
          if(res.success){
            let objModelArr = res.result
            if(objModelArr && objModelArr.length){
              that.getErModel(objModelArr[0]);
            }

          }else{
            that.messageUtil.warning(res.message)
          }

        }).finally(() => {
          that.spinning--
        })
      },
      validForm(){
        let VALIDATE_NO_PASSED = Symbol()
        return new Promise((resolve, reject) => {
          // 验证主表表单
          this.form.validateFields((err, values) => {
            err ? reject({ error: VALIDATE_NO_PASSED }) : resolve(values)
          })
        })
      },
      save(){
        return new Promise((resolve, reject) => {
          this.validForm().then(
            () => {
              this.saveData().then(()=>{
                resolve();
              })
            }
          )
        })
      },

      saveData(){
        let that = this
        that.spinning++
        let httpUrl = this.url.saveGenConfigAndTable
        let method = 'post'
        let sysGenConfig = Object.assign({}, this.iProps['sysGenConfig'])
        sysGenConfig.id = this.genConfigId;
        sysGenConfig.objCode = this.erModel.objCode
        //主表属性
        let sysGenTableMain = new Object();
        sysGenTableMain.id = "";
        sysGenTableMain.sysGenConfigId = this.genConfigId;
        sysGenTableMain.templateType = this.form.getFieldValue('templateType');
        sysGenTableMain.tableName = this.model.tableName;
        sysGenTableMain.tableDesc = this.erModel.relation.tableComment;
        sysGenTableMain.tableType = 'MAIN';
        sysGenTableMain.withAttachment = this.form.getFieldValue('withAttachment');
        sysGenTableMain.withFormWorkflow = this.form.getFieldValue('withFormWorkflow');
        sysGenTableMain.workflowSubmit = this.form.getFieldValue('workflowSubmit');
        sysGenTableMain.mainManangerLayout = this.form.getFieldValue('mainManangerLayout');
        sysGenTableMain.mainFormLayout = this.form.getFieldValue('mainFormLayout');
        sysGenTableMain.orderNo = 0;

        let subTableList = [];
        let subTableRelations = this.erModel.relation.children;
        if(subTableRelations && subTableRelations.length){
          sysGenTableMain.withSubTable = "true";
          subTableRelations.forEach(relation => {
            let subTable = {};
            subTable.id = "";
            subTable.sysGenConfigId = that.genConfigId;
            subTable.tableType = "SUB";
            subTable.templateType = sysGenTableMain.templateType;
            subTable.tableName = relation.tableKey;
            subTable.tableDesc = relation.tableComment;
            subTable.withAttachment = "";
            subTable.mainManangerLayout = "";
            subTable.orderNo = "";
            subTable.withSubTable = "false";
            subTableList.push(subTable);
          })
        }else{
          sysGenTableMain.withSubTable = "false";
        }
        sysGenConfig.mainTable = sysGenTableMain
        sysGenConfig.subTableList = subTableList
        let promise = new Promise(function(resolve, reject) {
          httpAction(httpUrl, sysGenConfig, method).then((res) => {
            if (res.success) {
              that.messageUtil.success(res.message)
              that.$emit("setGenConfigId",res.result);
              that.sysGenConfig.id = res.result
              sysGenConfig.id = res.result
              that.$emit('setProp', 'sysGenConfig', sysGenConfig)
              resolve(res.message)
            } else {
              that.messageUtil.warning(res.message)
              reject(res.message)
            }
          }).finally(() => {
            that.spinning--
          })
        });
        return promise;
      },
      getGenConfigAndTable(sysGenConfigId){
        let that = this
        that.spinning++
        let params = {
          sysGenConfigId:sysGenConfigId
        }
        getAction(this.url.queryBySysGenConfigId, params).then(res => {
          if(res.success){
            let sysGenConfig = res.result
            that.sysGenConfig = sysGenConfig
            that.$emit('setProp', 'sysGenConfig', sysGenConfig)
            this.form.resetFields()
            this.model = Object.assign({}, sysGenConfig.mainTable)
            this.$nextTick(() => {
              this.form.setFieldsValue(this.lodash.pick(this.model, Object.keys(this.validatorRules)))
            })
            if(sysGenConfig.actAppObject){
              this.getErModel(sysGenConfig.actAppObject)
            }

          }else{
            that.messageUtil.warning(res.message)
          }

        }).finally(() => {
          that.spinning--
        })
      },

    },
    watch: {
      genConfigId: {
        immediate: true,
        handler (value) {
          if (value) {
            this.getGenConfigAndTable(value)
          } else {

          }
        }
      },
      objCode:{
        immediate:true,
        handler(value){
          if(value){
            this.getObjModelByCode(value)
          }
        }
      }
    },
    created () {

    }
  }
</script>
